package com.example.demo.controller;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.annotations.Insert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.lang.model.element.ModuleElement;

@RestController
//@RequestMapping("/user")
public class UserController {

    @Autowired
    private static Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserMapper userMapper;

    //登录
    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest request)
    {
        //1.通过调用mapper层查看username和password是否存在并且匹配
          User user = userMapper.selectByName(username);
        if (user == null || !user.getPassword().equals(password))
        {
              //登录失败
              log.warn("登录失败,用户名或密码错误 "+ user);
              return new User();
        }

        //2.匹配成功则创建会话
          HttpSession session = request.getSession(true); //为true代表会话不存在则创建
          session.setAttribute("user",user); //方便后面getUserInfo方法使用
          user.setPassword(""); //防止泄露
          return user;
    }

    //注册
    @RequestMapping("/register")
    public Object register(String username,String password)
    {
        User user = null;
        try{
            user = new User(username,password);
            Integer ret = userMapper.insert(user);
            log.info("注册返回结果:" + ret);
            user.setPassword("");
        }catch(DuplicateKeyException e){ //如果用户名重名创建失败报异常
            log.warn("用户创建失败,用户名重复:" + username);
            return new User();
        }

        return user;
    }

    @RequestMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest request)
    {
        //1.从请求中获取到会话
        HttpSession session = request.getSession(false);
        if(session == null)
        {
            log.warn("用户未登录");
            return new User();
        }
        //2.从会话中获取到之前保存的用户对象
        User user = (User)session.getAttribute("user");
        if(user == null)
        {
            log.warn("session中获取不到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }

}
